const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const cron = require('node-cron');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 3000;

// 导入通知服务
const { checkAndPushReminders } = require('./services/notificationService');

// 中间件
app.use(cors()); // 允许跨域
app.use(bodyParser.json()); // 解析 JSON 请求体
app.use(bodyParser.urlencoded({ extended: true })); // 解析 URL 编码的请求体

// 请求日志中间件
app.use((req, res, next) => {
  console.log(`${new Date().toISOString()} - ${req.method} ${req.path}`);
  next();
});

// 路由
const authRoutes = require('./routes/auth');
const memosRoutes = require('./routes/memos');
const statisticsRoutes = require('./routes/statistics');

app.use('/api/auth', authRoutes);
app.use('/api/memos', memosRoutes);
app.use('/api/statistics', statisticsRoutes);

// 根路径
app.get('/', (req, res) => {
  res.json({
    message: '备忘录应用API',
    version: '1.0.0',
    endpoints: {
      auth: {
        register: 'POST /api/auth/register',
        login: 'POST /api/auth/login',
        profile: 'GET /api/auth/profile'
      },
      memos: {
        list: 'GET /api/memos',
        detail: 'GET /api/memos/:id',
        create: 'POST /api/memos',
        update: 'PUT /api/memos/:id',
        complete: 'PATCH /api/memos/:id/complete',
        delete: 'DELETE /api/memos/:id'
      },
      statistics: {
        basic: 'GET /api/statistics',
        priority: 'GET /api/statistics/priority',
        overview: 'GET /api/statistics/overview'
      }
    }
  });
});

// 404 错误处理
app.use((req, res) => {
  res.status(404).json({
    code: 404,
    message: '接口不存在'
  });
});

// 全局错误处理中间件
app.use((err, req, res, next) => {
  console.error('服务器错误:', err);
  res.status(500).json({
    code: 500,
    message: '服务器内部错误',
    error: err.message
  });
});

// 启动服务器
app.listen(PORT, () => {
  console.log('========================================');
  console.log(`🚀 服务器启动成功`);
  console.log(`📡 运行在: http://localhost:${PORT}`);
  console.log(`🕐 启动时间: ${new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })}`);
  console.log('========================================');
  
  // 启动定时任务：每分钟检查一次备忘录推送
  cron.schedule('* * * * *', () => {
    checkAndPushReminders();
  });
  
  console.log('⏰ 定时推送任务已启动（每分钟执行一次）');
  console.log('========================================');
  
  // 服务启动时立即执行一次检查
  checkAndPushReminders();
});

module.exports = app;
